package cn.rubintry.bug.hunting.fragment

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.viewbinding.ViewBinding
import cn.rubintry.animate.AnimateUtils
import cn.rubintry.bug.common.base.BaseFragment
import cn.rubintry.bug.hunting.R
import cn.rubintry.bug.hunting.activity.LoginActivity
import cn.rubintry.bug.hunting.activity.SettingActivity
import cn.rubintry.bug.hunting.databinding.FragmentMineBinding
import cn.rubintry.bug.hunting.common.event.LoginEvent
import cn.rubintry.bug.hunting.common.extension.paddingTop
import cn.rubintry.bug.hunting.common.http.viewmodel.MineViewModel
import cn.rubintry.bug.hunting.common.manager.UserManager

import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.google.android.material.appbar.AppBarLayout
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.SmartGlideImageLoader
import jp.wasabeef.glide.transformations.BlurTransformation
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.math.abs


/**
 * 我的
 */
class MineCoordinatorLayoutFragment() : BaseFragment<FragmentMineBinding>(), AppBarLayout.OnOffsetChangedListener,
    View.OnClickListener {

    private val mineViewModel : MineViewModel by viewModels<MineViewModel>()


    override fun layoutId(): Int {
        return R.layout.fragment_mine
    }


    override fun initView() {
        binding?.flexibleExampleAppbar?.addOnOffsetChangedListener(this)
        binding?.imgHeader?.setOnClickListener(this)
        binding?.tvMineNickName?.setOnClickListener(this)
        binding?.imgSettings?.setOnClickListener(this)
        val toolbarLayoutParams = binding?.flexibleMineToolbar?.layoutParams
        toolbarLayoutParams?.let {
            it.height += BarUtils.getStatusBarHeight()
            binding?.flexibleMineToolbar?.layoutParams = it
        }
        binding?.flexibleMineToolbar?.paddingTop(BarUtils.getStatusBarHeight())

        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }
    }


    override fun observeData() {
        mineViewModel.imageData.observe(this) { data ->
            if(data.code == "0"){
                data?.data?.let {
                    binding?.imgMineBg?.let {
                        Glide.with(this)
                            .load(data.data[0].url)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .transform(BlurTransformation(25, 1) , CenterCrop())
                            .skipMemoryCache(true)
                            .into(it)
                    }
                }
            }
        }
    }

    override fun bindingClazz(): Class<out ViewBinding> {
        return FragmentMineBinding::class.java
    }

    override fun onNetWorkError(msg: String) {

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mineViewModel.getHomeBackgroundImages()
        if(UserManager.getInstance().isLogin()){
            binding?.tvMineNickName?.text = UserManager.getInstance().getUserData()?.detail?.userName
            UserManager.getInstance().getUserData()?.detail?.headerUrl?.let { url ->
                Glide.with(this)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(binding?.imgHeader!!)
            }
        }else{
            Glide.with(this)
                .load(R.mipmap.mlogo)
                .transform(CenterCrop())
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(binding?.imgHeader!!)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onOffsetChanged(appBarLayout : AppBarLayout, i: Int) {
        val alpha = abs(i).toFloat() / appBarLayout.totalScrollRange
        val headerScale = (1 + (1 - alpha) * 0.8).toFloat()
        binding?.imgHeader?.scaleX = headerScale
        binding?.imgHeader?.scaleY = headerScale
        binding?.imgHeader?.translationX = (1 - alpha) * SizeUtils.dp2px(50f) + SizeUtils.dp2px(20f)
        binding?.imgHeader?.translationY = (1 - alpha) * (SizeUtils.dp2px(50f)) + BarUtils.getStatusBarHeight() + SizeUtils.dp2px(10f)

        binding?.tvMineNickName?.setTextColor(Color.rgb((255 * (1 - alpha)).toInt(), (255 * (1 - alpha)).toInt(), (255 * (1 - alpha)).toInt()))
        binding?.tvMineNickName?.scaleX = (1 + (1 - alpha) * 0.5).toFloat()
        binding?.tvMineNickName?.scaleY = (1 + (1 - alpha) * 0.5).toFloat()
        binding?.tvMineNickName?.translationX = (1 - alpha) * SizeUtils.dp2px(90f) + SizeUtils.dp2px(75f)
        binding?.tvMineNickName?.translationY = (1 - alpha) * (SizeUtils.dp2px(40f)) + BarUtils.getStatusBarHeight() + SizeUtils.dp2px(13f)
        //全透明的时候禁止点击
        binding?.imgSettings?.isEnabled = alpha != 0f
        binding?.flexibleMineToolbar?.alpha = alpha

        if(alpha == 0f){
            if(!AnimateUtils.with(binding?.imgHeader).hasAnimator()){
                AnimateUtils.with(binding?.imgHeader)
                    .scale(headerScale , headerScale * 1.05f , true)
                    .enableLoop(true)
                    .setDuration(1000)
                    .start()
            }
        }else{
            AnimateUtils.with(binding?.imgHeader).cancel()
        }
    }

    override fun onClick(v: View?) {
        when(v){
            binding?.imgHeader -> {
                if(!UserManager.getInstance().isLogin()){
                    startActivity(Intent(requireContext() , LoginActivity::class.java))
                    return
                }
                XPopup.Builder(requireContext())
                    .asImageViewer(null , UserManager.getInstance().getUserData()?.detail?.headerUrl ?: "" , SmartGlideImageLoader())
                    .isShowSaveButton(false)
                    .show()
            }

            binding?.tvMineNickName -> {
                if(!UserManager.getInstance().isLogin()){
                    startActivity(Intent(requireContext() , LoginActivity::class.java))
                }
            }

            binding?.imgSettings -> {
                startActivity(Intent(requireContext() , SettingActivity::class.java))
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginEvent(event: LoginEvent){
        if(event.success){
            binding?.tvMineNickName?.text = UserManager.getInstance().getUserData()?.detail?.userName
            UserManager.getInstance().getUserData()?.detail?.headerUrl?.let { url ->
                Glide.with(this)
                    .load(url)
                    .transform(CenterCrop())
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(binding?.imgHeader!!)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

}